import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components/native';
import { Animated } from 'react-native';
import Touchable from '@appandflow/touchable';

import { colors } from '../../utils/constants';
import { ANIM_IDLE, ANIM_MOVE_TO_LEFT, ANIM_MOVE_TO_RIGHT } from '../../types';

const TAB_WIDTH = 72;
const INDICATOR_WIDTH = TAB_WIDTH * 0.35;
const TAB_MARGIN = 5; // Tab标签之间的间距
const INDICATOR_DURATION = 200; // 游标移动动画的持续时间

const caculateIndicatorX = (index) => (index * TAB_WIDTH + (TAB_WIDTH - INDICATOR_WIDTH) / 2);

const Root = styled.View`
  width: ${props => props.tabNumber * TAB_WIDTH};
  height: 100%;
`;

const Indicator = styled.View`
  width: ${props => props.width || INDICATOR_WIDTH};
  height: 4;
  backgroundColor: ${colors.ACTIONBAR_TAB_INDICATOR};
  position: absolute;
  bottom: 4;
  borderRadius: 2;
  left: ${props => props.left || caculateIndicatorX(props.selectIndex)};
`;

const IndicatorAnimView = Animated.createAnimatedComponent(Indicator);

const Tabs = styled.View`
  flex: 1;
  flexDirection: row;
  justifyContent: center;
  alignItems: center;
`;

const Tab = styled(Touchable).attrs({
  feedback: 'none'
})`
  flex: 1;
  alignItems: center;
  marginLeft: ${TAB_MARGIN};
  marginRight: ${TAB_MARGIN};
  borderColor: blue;
  borderWidth: 1;
`;

const TabText = styled.Text`
  fontSize: 18;
  color: ${props => props.isSelected ? colors.ACTIONBAR_TEXT_SELECTED : colors.ACTIONBAR_TEXT_NORMAL};
`;

class ToolbarTabs extends Component {

  state = {
    currentTab: this.props.selectIndex ? this.props.selectIndex : 0,
    nextTab: 0,
    indicatorW: new Animated.Value(INDICATOR_WIDTH),
    animProgress: new Animated.Value(0), // 这个参数用于控制动画执行的过程，区间为0~1
    animDirection: ANIM_IDLE // 用于记录当前游标是往左还是右移动
  }

  componentWillReceiveProps(nextProps) {
    this._updateIndicator(nextProps.selectIndex);
    this.setState({ currentTab: nextProps.selectIndex });
  }

  get getCurrentTabIndex() {
    return this.state.currentTab;
  }

  /**
   * 该动画分为2个阶段，第一个阶段向动画移动方向伸展长度，当达到最大长度之后，从游标的另一端缩短长度，直至
   * 到达游标的普通状态下的长度
   *
   * @param direction 游标移动的方向
   * @param process 动画当前进行的百分比
   */
  moveIndicator = (direction = ANIM_IDLE, process = 0) => {
    const totalDeltaW = TAB_MARGIN / 2 + TAB_WIDTH;
    let indicatorW = INDICATOR_WIDTH;
    if (process <= 0.5) {
      // 第一阶段，伸长宽度
      indicatorW += totalDeltaW * process * 2;
    } else {
      // 第二阶段，缩短宽度
      indicatorW -= totalDeltaW * process * 2;
    }
    this.setState({ indicatorW });
  }

  _animIndicator = index => {
    this.state.animProgress.setValue(0);
    Animated.timing(this.state.animProgress, {
      toValue: 1,
      duration: INDICATOR_DURATION,
      useNativeDriver: false
    }).start(() => {
      this.setState({
        currentTab: this.state.nextTab,
        animDirection: ANIM_IDLE
      });
    });
    if (this.props.onTabChanged) this.props.onTabChanged(index);
  }

  _updateIndicator = index => {
    if (index === this.state.selectIndex) return;
  }

  /**
   * 用户点击tab标签之后，游标移动的方向
   *
   * @param index 用户点击的tab的索引号
   */
  _getDirection = (index = 0) => index < this.state.currentTab ? ANIM_MOVE_TO_LEFT : ANIM_MOVE_TO_RIGHT

  render() {
    const calcIndicatorWidth = this.state.animProgress.interpolate({
        inputRange: [0, 0.5, 1],
        outputRange: [INDICATOR_WIDTH, TAB_MARGIN / 2 + TAB_WIDTH + INDICATOR_WIDTH, INDICATOR_WIDTH]
      });

    const calcIndicatorLeftMoveToRight = this.state.animProgress.interpolate(
      this.state.animDirection === ANIM_MOVE_TO_RIGHT ?
      {
        inputRange: [0, 0.5, 1],
        outputRange: [
          caculateIndicatorX(this.state.currentTab),
          caculateIndicatorX(this.state.currentTab),
          caculateIndicatorX(this.state.nextTab)
        ]
      } :
      {
        inputRange: [0, 0.5, 1],
        outputRange: [
          caculateIndicatorX(this.state.currentTab),
          caculateIndicatorX(this.state.nextTab),
          caculateIndicatorX(this.state.nextTab)
        ]
      }
    );

    const { tabs = [] } = this.props;

    return (
      <Root tabNumber={tabs.length}>
        <Tabs>
        {
          tabs.map((tab, index) => (
              <Tab
                isSelected={this.state.currentTab === index}
                key={tab.id}
                onPress={() => {
                  if (this.state.animDirection === ANIM_IDLE && this.state.currentTab !== index) {
                    this.setState({
                      nextTab: index,
                      animDirection: this._getDirection(index)
                    }, () => this._animIndicator(index));
                  }
                }}
              >
                <TabText isSelected={this.state.currentTab === index}>{tab.title || 'TAB'}</TabText>
              </Tab>
            ))
        }
        </Tabs>
        <IndicatorAnimView
          selectIndex={this.state.currentTab}
          left={calcIndicatorLeftMoveToRight}
          width={calcIndicatorWidth}
        />
      </Root>
    );
  }
}

ToolbarTabs.propTypes = {
  onTabChanged: PropTypes.func,
}

export default ToolbarTabs;
